import { Component, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { JsonEditorComponent, JsonEditorOptions } from '@app/shared/common/json-editor/json-editor.component';
import { HttpClient} from '@angular/common/http';
import { AppConsts } from '@shared/AppConsts';
import { ConfigDataItem, ConfigFileDto, CustomConfigServiceProxy, IEntityDtoOfGuid, PagedCustomConfigDto, PagedResultDtoOfConfigDataItem } from '@shared/service-proxies/service-proxies';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { finalize } from 'rxjs/operators';
import { AppModalComponentBase } from '@shared/common/app-modal-component-base';
import { IJsonEditorModalCallbackData, JsonEditorModalComponent } from '@app/shared/common/json-editor/json-editor-modal.component';
import { LazyLoadEvent } from 'primeng/api';
import { CustomConfigModalComponent } from '../customConfig/custom-config-modal.component';
import { Table } from 'primeng/table';
import { Paginator } from 'primeng/paginator';

@Component({
    selector: 'lookup-content-config-modal',
    templateUrl: './lookup-content-config-modal.component.html'
})
export class LookupContentConfigModalComponent extends AppModalComponentBase {

    @ViewChild('modal', { static: true }) modal: ModalDirective;
    
    @Output() callback: EventEmitter<string> = new EventEmitter<string>();

    private dataType : string ;
    title: string;

    @ViewChild('dataTable', { static: true }) dataTable: Table;
    @ViewChild('paginator', { static: true }) paginator: Paginator;
    @ViewChild('editConfigModal', { static: true }) editConfigModal: CustomConfigModalComponent;
    @ViewChild('jsonEditorModal', { static: true }) jsonEditorModal: JsonEditorModalComponent;
    
    loading = false;

    filterText: string = '';

    selectedDatas: IEntityDtoOfGuid[];

    constructor(
        injector: Injector,
        private http: HttpClient,
        private _customConfigServiceProxy: CustomConfigServiceProxy
    ) {
        super(injector);
    }

   
    show( dataType: string, title: string) {
        this.dataType = dataType;
        this.title = title;
        this.modal.show();

        this.getListData(null);
    }

    close(): void {
        this.modal.hide();
    }

    selectItem(record: ConfigDataItem) {
        this.callback.emit(record.customKey);
        this.modal.hide();
    }

    create() {
        this.editConfigModal.show(null, '');
    }

    editConfig(record: PagedCustomConfigDto) {
        this.editConfigModal.show(record.id, record.name);
    }

    reloadPage() {
        if (this.primengTableHelper.TryChangePage(this.paginator, this.paginator.getPage())) {
            return;
        }

        this.getListData(null);
    }

    getListData(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            if (this.primengTableHelper.TryChangePage(this.paginator, 0)) {
                return;
            }
        }

        this.primengTableHelper.showLoadingIndicator();
        this._customConfigServiceProxy.getPagedConfigDatasByType(
            this.dataType,
            this.filterText,
            this.primengTableHelper.getSorting(this.dataTable),
            this.primengTableHelper.getMaxResultCount(this.paginator, event),
            this.primengTableHelper.getSkipCount(this.paginator, event)
        ).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
        .subscribe(result => {
            this.primengTableHelper.totalRecordsCount = result.totalCount;
            this.primengTableHelper.records = result.items;
            this.primengTableHelper.hideLoadingIndicator();
        });
    }

        
    delete() { 
        if (!this.selectedDatas) return;
        let ids = this.selectedDatas.map(item=>item.id);
        if (ids.length == 0) return;
        this.message.confirm(this.l('DeleteWarningMessage'), this.l('AreYouSure'),
            (isConfirmed) => {
                if (!isConfirmed) return;
                this._customConfigServiceProxy.deleteList(ids)
                    .subscribe(() => {
                        this.selectedDatas =[];
                        this.reloadPage();
                        this.notify.success(this.l('SuccessfullyDeleted'));
                    });
            })
    }

    config() {
        this.loading = true;
        this._customConfigServiceProxy.getConfigFileContent()
        .pipe(finalize(() => this.loading = false))
        .subscribe(result => {
            let data: any ={};
            try{
                data = JSON.parse(result);
            }catch(e){
                console.log(e);
            }
            
            this.jsonEditorModal.configure({
                message: 'config',
                data: data,
                schema : this.configSchema
            });
            this.jsonEditorModal.show();
        });
    }
    readonly configSchema: any = {
        'type': 'object',
        'title': 'The Root Schema',
        'required': [
          'Default',
          'Custom'
        ],
        'properties': {
          'Default': {
            'type': 'object'
          },
          'Custom': {
            'type': 'object'
            }
          }
        };
      
    configSave(e:IJsonEditorModalCallbackData){
        this.loading = true;
        this._customConfigServiceProxy.updateOrCreateConfigFile(new ConfigFileDto({content: e.data}))
        .pipe(finalize(() => this.loading = false))
        .subscribe(result => {
            this.notify.success(this.l('SavedSuccessfully'));
        });
    }
}
